<?php
/**
 * 成员数据模型
 */

class MemberModel extends RelationModel {
    protected $_auto = array(
        array('password', md5, 1, 'function')
    );

    protected $_validate = array(
        array('email', 'require', '邮箱必须！', 1),
        array('email', 'email', '邮箱格式错误！', 0),
        array('email', '', '邮箱已经被注册！', 0, 'unique', 1),

        array('password', 'require', '密码必须！', 1, null, 1),
        array('password2', 'require', '确认密码必须！', 1, null, 1),
        array('password2', 'password', '两次密码不相同', 1, 'confirm', 1),

        array('post_id', 'hadPost', '没有该职位', 1, 'callback', 2)
    );


	protected $_link = array(
		'role' => array(
			'mapping_type' => BELONGS_TO,
			'class_name' => 'role',
		),
		'post' => array(
			'mapping_type' => BELONGS_TO,
			'class_name' => 'post',
		),
	);

    protected function _after_select(&$results, $options) {
        parent::_after_select($results, $options);
        foreach ($results as &$result)
            $this->pullRelations($result);
    }

    protected function _after_find(&$result, $options) {
        parent::_after_find($result, $options);
        $this->pullRelations($result);
    }

    protected function pullRelations(&$result) {
        $result['department'] = D('department')->where(array(
            'id' => $result['post']['department_id']))->find();
        $result['session'] = D('session')->where(array(
            'id' => $result['department']['session_id']))->find();
    }

    protected function hadPost($post_id) {
        return M('Post')->where(array('id' => $post_id))->getField('id') != null;
    }
}
